<template>
<div>
  <custom-modal
    v-if="visible"
    :fullscreen="false"
    :visible="visible"
    :title="$t('publishStrategy')"
    :destroyOnClose="true"
    :maskClosable="false"
    :bodyStyle="{ height: '500px' }"
    :width="1200"
    :suring="confirmLoading"
    @cancel="handleCancel"
    @ok="submitPublishData"
    class="publishStrategyModal">

    <a-form-model
      layout="horizontal"
      class="AsteriskAfter newEditStyle"
      ref="formComp"
      :rules="rules"
      :model="formData">
      <a-row :gutter="24">
        <a-col :md="12">
          <a-form-model-item :label="$t('mztjTestTask')" prop="taskId">
            <a-spin :spinning="loaddingTestLists">
              <common-select
                :options="testOptions"
                :loading="false"
                :default-value="formData.taskId"
                :allow-clear="false"
                @changeoption="formData.taskId = $event"></common-select>
            </a-spin>
          </a-form-model-item>
        </a-col>
        <a-col :md="12">
          <a-form-model-item :label="$t('OTA通道测试报告')" prop="testReportFileId"
                         :rules="{required: true,message: '请上传文件'}">
            <FileUploader v-model="formData.testReportFileId"/>
            <!--        TODO: 限制文件类型    :accept="['.xls','.xlsx']"-->
          </a-form-model-item>
        </a-col>
      </a-row>
      <FotaUpdateStrategy :id="strategyId" :isReadonly="true" style="height:300px;"/>
      <a-form-model-item :label="$t('条件策略名称')">
        <a @click="showConditionStrategyDetail">{{conditionStrategyName}}</a>
      </a-form-model-item>
      <a-form-model-item :label="$t('remark')" prop="remark">
        <custom-text-area @change="formData.remark = $event" :val="formData.remark" :rows="3" :max-len="200">
        </custom-text-area>
      </a-form-model-item>
      <a-form-model-item :label="$t('strategyAudit')">
        <div style="height:360px;margin-bottom:16px">
          <full-parent-dom-with-dask :loading="loadingProcess"></full-parent-dom-with-dask>
          <process-viewer
            :key="`designer-${processView.index}`"
            v-if="processView.index"
            :xml="processView.xmlData"
            style="height:100%" />
        </div>
        <audit-flow-process ref="auditProcessRef" method-name="getPoliceFlowDesinNodeData"></audit-flow-process>
      </a-form-model-item>
    </a-form-model>
  </custom-modal>
  <!-- 条件策略详情 -->
    <custom-modal
      :visible="conditionVisible"
      title="条件策略详情"
      :destroyOnClose="true"
      @cancel="handleCancelEcuVersion"
      :isOkBtn="false"
      class="largeVersionPopup"
      modalCls=".largeVersionPopup"
      :bodyStyle="{ height: '500px', overflowY: 'auto'}">
      <FotaConditionStrategy :id="conditionStrategyId"/>
    </custom-modal>
</div>
</template>
<script>
import CustomModal from '@/components/CustomModal/index.vue'
import CommonSelect from '@/components/SelfComponents/CommonSelect.vue'
import CustomTextArea from '@/components/CustomTextArea/index.vue'
import AuditFlowProcess from '@/views/components/AuditFlowProcess/config.vue'
import { publishStrategyFormData } from '../config/form'
import { checkTextLen } from '@/utils/validate'
import ProcessViewer from '@/components/ProcessViewer'
import flowDesignApi from '@/api/modules/flowManage/flowDesign'
import FullParentDomWithDask from '@/components/LoadDataSpin/FullParentDomWithDask.vue'
import FileUploader from '@/components/Upload/FileUploader'
import FotaUpdateStrategy from '@/views/strategy/FotaUpdate/components/ViewStrategy.vue'
import FotaConditionStrategy from '@/views/strategy/FotaCondition/components/ViewStrategy.vue'
const initProcessView = {
  index: '',
  xmlData: ''
}
export default {
  components: {
    CustomModal,
    CommonSelect,
    CustomTextArea,
    AuditFlowProcess,
    ProcessViewer,
    FileUploader,
    FullParentDomWithDask,
    FotaUpdateStrategy,
    FotaConditionStrategy
  },
  props: {
    versionType: {
      type: String,
      default: ''
    },
    upgradeTriggerType: {
      type: String,
      default: ''
    },
    strategyId: {
      type: String,
      default: ''
    },
    taskId: {
      type: String,
      default: ''
    },
    processId: {
      type: String,
      default: 'Process_cl1:1:02483d56-54f6-11ed-866a-f89e942d9d49'
    }
  },
  data () {
    return {
      conditionVisible: false,
      conditionStrategyId: undefined,
      conditionStrategyName: '',
      confirmLoading: false,
      loaddingTestLists: true,
      visible: false,
      formData: { ...publishStrategyFormData },
      rules: {
        taskId: [{ required: true, trigger: 'blur', message: this.$t('pleaseInput') }],
        remark: [{ validator: checkTextLen(200) }]
      },
      testOptions: [],
      processView: {
        ...initProcessView
      },
      loadingProcess: false
    }
  },
  watch: {
    visible: {
      handler (val) {
        if (val) {
          this.initData()
        } else {
          this.resetData()
        }
      }
    }
  },
  methods: {
    handleCancelEcuVersion(){
      this.conditionVisible = false
    },
    showConditionStrategyDetail(){
      this.conditionVisible = true
    },
    handleCancel () {
      this.visible = false
    },
    switchVisible (val) {
      this.visible = val
    },
    getStrategyInfo(){
      this.$store.dispatch('getStrategyDetailData', {id: this.strategyId}).then((res) => {
        this.conditionStrategyName = res.data.conditionStrategyName
        this.conditionStrategyId = res.data.conditionStrategyId
      })
    },
    initData () {
      if (!this.strategyId) {
        return
      }
      this.formData.id = this.strategyId
      this.getTestData()
      this.getStrategyInfo()
      this.getProcessXmlData()
    },
    // 获取某策略下的所有测试数据
    getTestData () {
      this.testOptions = []
      this.formData.taskId = ''
      this.loaddingTestLists = true
      this.$store.dispatch('getTaskSelectData', {
        type: [9, 10, 8],
        strategyId: this.strategyId
      }).then((res) => {
        if (res.data && res.data.length === 0) {
          return
        }
        this.testOptions = res.data.map(item => {
          let { name } = item
          if (item.type === 10) {
            name += '[' + this.$t('cycleTestTask') + ']'
          }
          return {
            name,
            id: item.id,
            status: item.status
          }
        })
        if (this.taskId) {
          this.formData.taskId = this.taskId
          return
        }
        if (res.data[0] && res.data[0].id) {
          this.formData.taskId = res.data[0].id
        }
      }).finally(() => {
        this.loaddingTestLists = false
      })
    },

    resetData () {
      this.formData = { ...publishStrategyFormData }
      this.processView = { ...initProcessView }
    },
    async submitPublishData () {
      await this.$refs.formComp.validate();
      const auditConfigData = this.$refs.auditProcessRef.getConfigsData()
      this.confirmLoading = true
      let data
      if (auditConfigData === 'noNeedRole') {
        data = { ...this.formData }
      } else if (auditConfigData.length === 0) {
        this.confirmLoading = false
        return
      } else {
        data = { ...this.formData, candidates: auditConfigData }
      }
      data.versionType = this.versionType;
      data.upgradeTriggerType = this.upgradeTriggerType;
      data.testReportFileId = [...this.formData.testReportFileId].map(a => a.id)
      this.$store.dispatch('publishStrategyData', data).then(() => {
        this.visible = false
        this.$emit('published')
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    // 获取流程图
    getProcessXmlData () {
      this.loadingProcess = true
      flowDesignApi.getPoliceFlowDesinXmlData().then(res => {
        this.processView.index = 'process' + Math.random
        this.processView.xmlData = res.data
      }).finally(() => {
        this.loadingProcess = false
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>
